<template>
	<view class="roc-date-picker">
		<view @click="handleDatePickerShow()">
			<u-input
				v-model="value"
				disabled
				disabledColor="#ffffff"
				:placeholder="item.props.placeholder || '请选择'"
				:clearable="item.props.clearable || true"
				border="none"
			></u-input>
		</view>
		<uni-icons
			class="uni-icons"
			@click="handleClearable"
			v-if="(item.props.clearable || true) && (!item.props.readonly) && (!item.props.disabled) && value"
			type="clear"
			color="#e1e1e1"
			size="14"
		></uni-icons>
		<!-- 弹窗相关 -->
		<u-datetime-picker
			:show="datePickerShow"
			itemHeight="88"
			:mode="datePickerType"
			closeOnClickOverlay
			@cancel="datePickerCancel"
			@close="datePickerCancel"
			@confirm="datePickerConfirm"
		></u-datetime-picker>
	</view>
</template>

<script>
export default {
	name: 'roc-date-picker',
	props: {
		item: {
			type: Object,
			default() {
				return {};
			}
		},
		value: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			// 日期选择器是否显示
			datePickerShow: false,
			// 日期选择器的类型
			datePickerType: ''
		};
	},
	watch: {
		item: {
			handler(newVal) {
				// 自动显示当前时间
				if(newVal.value) {
					this.$emit('input', newVal.value);
				}
			},
			immediate: true
		}
	},
	methods: {
		// 处理清空选中值
		handleClearable() {
			this.$emit('input', '');
		},
		// 处理 日期选择器 显示 & 规则
		handleDatePickerShow() {
			if (this.item.props.readonly || this.item.props.disabled) return;
			this.datePickerShow = true;
			this.handleDatePickerType(this.item.props.type);
		},
		// 处理 日期选择器的类型
		handleDatePickerType(val) {
			if (val == 'datetime') {
				this.datePickerType = 'datetime';
			} else if (val == 'date') {
				this.datePickerType = 'date';
			} else if (val == 'month') {
				this.datePickerType = 'year-month';
			} else {
				this.datePickerType = 'date';
			}
		},
		// 日期选择器 取消 | 关闭
		datePickerCancel() {
			this.datePickerShow = false;
		},
		// 日期选择器 确定 | 关闭
		datePickerConfirm(e) {
			// this.$set(this.form, this.item.field, this.datePickerResult(e.value, e.mode));
			this.$emit('input', this.datePickerResult(e.value, e.mode));
			this.datePickerShow = false;
		},
		// 日期时间确定后返回的数据格式处理
		datePickerResult(time, mode) {
			const timeFormat = uni.$u.timeFormat;
			switch (mode) {
				case 'datetime':
					return timeFormat(time, 'yyyy-mm-dd hh:MM');
				case 'date':
					return timeFormat(time, 'yyyy-mm-dd');
				case 'year-month':
					return timeFormat(time, 'yyyy-mm');
				case 'time':
					return time;
				default:
					return '';
			}
		}
	}
};
</script>

<style lang="scss">
.roc-date-picker {
	position: relative;
	width: 100%;
	.uni-icons {
		position: absolute;
		right: 0;
		top: 50%;
		z-index: 9;
		transform: translateY(-50%);
	}
}
</style>
